//
//  MapNaviManager.swift
//  ezyform
//
//  Created by Moennig Q on 2/9/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import CoreLocation
import MapKit

enum MapOptions: String{
    case googleMap = "Goole Map"
    case appleMap  = "Apple Map"
}

class MapNavigationHelper {
    
    static let shared = MapNavigationHelper()
    func showMapsOptions(_ model: DeliveryWarehouseModel,vc: BaseViewController){
        
        let longitude = model.longitude
        let latitude = model.latitude
        let navigationStreetString = model.map_full_address
        //
        var cellList = [CellModel]()
        cellList.removeAll()
        //1.Google Map
        cellList.append(CellModel(title: MapOptions.googleMap.rawValue))
        //2.设备是否安装了Apple Maps
        if let url = URL(string: "maps://"),  UIApplication.shared.canOpenURL(url) {
            cellList.append(CellModel(title: MapOptions.appleMap.rawValue))
        }
        let actionSheetView = CustomActionSheet(title: "Map options", aCellArray: cellList, aCancelModel: CellModel(title: R.string.localizable.cancel()), aSelectedClosure: { [weak self](row) in
            guard let strongSelf = self else {return}
            switch cellList[row].title {
            case MapOptions.googleMap.rawValue:
                strongSelf.doGoogleNavigation(latitude: latitude, longitude: longitude, destination: navigationStreetString)
            case MapOptions.appleMap.rawValue:
                strongSelf.doAppleNavigation(latitude: latitude , longitude: longitude, destination: navigationStreetString)
            default:
                break
            }
        }, aCancelClosure: nil)
        vc.navigationController?.view.addSubview(actionSheetView)
    }
    //
    /**
     * 苹果地图路线规划
     * 文档：https://developer.apple.com/documentation/mapkit/mkmapitem
     */
    func doAppleNavigation(latitude: String,longitude: String,destination: String) {
        //1.先校验是否安装了Apple  map app
        //2.安装了直接调到Apple Map
        var toLocation: MKMapItem!
        if let doubleLatitude = Double(latitude), let doubleLongitude = Double(longitude), latitude != "" && longitude != "" {//从对当前位置导航到目的地
            let loc = CLLocationCoordinate2DMake(doubleLatitude, doubleLongitude)
            toLocation = MKMapItem(placemark:MKPlacemark(coordinate:loc,addressDictionary:nil))
            toLocation.name = destination
            //driving 模式，一个地址，表示从当前地址导航到toLocation，两个MKMapItem表示从第一个item导航到第二个item
            MKMapItem.openMaps(with: [toLocation], launchOptions: [
                MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])

        }else {//根据地址打开地图app查找地址
        //文档位置https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
            var urlString = "http://maps.apple.com/?saddr=&daddr=\(destination)&dirflg=d&t=s"
            urlString = urlString.replacingOccurrences(of: "\n", with: " ").replacingOccurrences(of: " ", with: "+")
            if let url = URL(string: urlString){
                if UIApplication.shared.canOpenURL(url){
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            }
        }
    }
    /**
     * 谷歌地图路线规划
     * 文档：https://developers.google.com/maps/documentation/ios/urlscheme
     */
    func doGoogleNavigation(latitude: String,longitude: String,destination: String ) {
        //1.先校验是否安装了google  map app
        //2.安装了直接调到Google Map
        //3.没有安装直接跳转到浏览器的Google Map
        var urlString = ""
        if latitude != "" && longitude != "" {
            //如果要显示用户当前位置的路线,请将该字段saddr留空,然后在字段daddr中输入目标坐标
            urlString = "comgooglemaps-x-callback://?saddr=&daddr=\(latitude),\(longitude)&directionsmode=driving"
        }else{
            urlString = "comgooglemaps://?q=\(destination)&directionsmode=driving"
        }
        //
        urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        urlString = urlString.replacingOccurrences(of: "\n", with: " ").replacingOccurrences(of: " ", with: "%20")
        if let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) {//安装了Google Map APP
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }else {//没有安装Google Maps app，打开浏览器
            if latitude != "" && longitude != "" {//根据经纬度
                urlString = "https://www.google.com/maps/search/?api=1&query=\(latitude),\(longitude)&directionsmode=driving"
            }else {//根据地址
                urlString = "https://www.google.com/maps/search/?api=1&query=\(destination)&directionsmode=driving"
            }
//            urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            //Replace line breaks and white spaces in the address with queryable values
            urlString = urlString.replacingOccurrences(of: "\n", with: " ").replacingOccurrences(of: " ", with: "+")
            if let urlDestination = URL(string: urlString),  UIApplication.shared.canOpenURL(urlDestination) {
                UIApplication.shared.open(urlDestination, options: [:], completionHandler: nil)
            }
        }
    }
}
